package com.wmz.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wmz.constant.AuthConstants;
import com.wmz.domain.LoginSysUser;
import com.wmz.mapper.LoginSysUserMapper;
import com.wmz.model.SecurityUser;
import com.wmz.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @author wmz
 * @date 2024/7/2 21:56
 * @description 商城后台管理系统用户登录策略实现类
 */
@Service(value = AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {
    @Autowired
    private LoginSysUserMapper loginSysUserMapper;
    @Override
    @Transactional
    public UserDetails realLogin(String username) {
        //根据用户名查询用户信息
        LoginSysUser loginSysUser = loginSysUserMapper
                .selectOne(new LambdaQueryWrapper<LoginSysUser>()
                .eq(LoginSysUser::getUsername, username));
        if(ObjectUtils.isNotEmpty(loginSysUser)) {
            //根据用户标识查询用户权限
            Set<String> loginPerms = loginSysUserMapper.selectLoginPermsByUserId(loginSysUser.getUserId());
            //创建安全用户对象SecurityUser进行封装
            SecurityUser securityUser = new SecurityUser();
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setStatus(loginSysUser.getStatus());
            securityUser.setShopId(loginSysUser.getShopId());
            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            //判断用户权限是否为空
            if(CollectionUtil.isNotEmpty(loginPerms) && loginPerms.size() > 0) {
                securityUser.setPerms(loginPerms);
            }
            return securityUser;
        }
        return null;
    }
}
